package geppetto.phraseHMM.phraseExtraction.extractedphrase.data;

import geppetto.phraseHMM.phraseExtraction.extractedphrase.ExtractedPhrasePairData;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;

public class AdaptationTypeData extends ExtractedPhrasePairData{
	HashMap<String, Double> types = new HashMap<String, Double>();

	public AdaptationTypeData() {
		super();
	}

	public void insert(String key, Double value){
		if(!types.containsKey(key)){
			types.put(key, 0d);
		}
		types.put(key, types.get(key) + value);
	}
	
	public Double getValue(String key){
		if(types.containsKey(key)){
			return types.get(key);
		}
		return 0d;
	}
	
	public Set<String> getKeyset(){
		return types.keySet();
	}

	@Override
	public void merge(ArrayList<HashMap<String, ExtractedPhrasePairData>> generalData, ArrayList<ExtractedPhrasePairData> data){		
		for(ExtractedPhrasePairData d : data){
			if(d instanceof AdaptationTypeData){
				AdaptationTypeData adaptData = (AdaptationTypeData) d;
				merge(adaptData);
			}
			else{
				System.err.println("trying to merge an instance of LexicalWeightData to with another type of class");
				System.exit(-1);
			}
		}
	}

	@Override
	public String toString() {
		String ret = "";
		for(String key : types.keySet()){
			Double value = types.get(key);
			ret += key + ":" + value + " ";
		}
		return ret;
	}
	
	public static AdaptationTypeData parseString(String s) {
		String[] typeCounts = s.split("\\s+");
		AdaptationTypeData data = new AdaptationTypeData();
		for(String type : typeCounts){
			String[] typeKeyValue = type.split(":");
			data.insert(typeKeyValue[0], Double.parseDouble(typeKeyValue[1]));
		}
		return data;
	}
	
	public void merge(AdaptationTypeData newData){
		for(String key : newData.getKeyset()){
			this.insert(key, newData.getValue(key));
		}
	}
	
	public void normalize(){
		double total = 0;
		for(String key : types.keySet()){
			total += types.get(key);
		}
		for(String key : types.keySet()){
			types.put(key, types.get(key) / total);
		}
	}
}
